package io.renren.controller;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.renren.common.utils.RequestDataExtractor;
import io.renren.common.utils.Sign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhengd
 */
@Slf4j
public class BaseController {

    @Autowired
    protected HttpServletRequest request;

    public String getUserId(){
        DecodedJWT decodedJWT = common();
        String userId = decodedJWT.getClaims().get(Sign.CLAIM_USER_ID).asString();
        return userId;
    }

    public String getDeptId(){
        DecodedJWT decodedJWT = common();
        String deptId = decodedJWT.getClaims().get(Sign.CLAIM_DEPT_ID).asString();
        return deptId;
    }

    public String getUserNo(){
        DecodedJWT decodedJWT = common();
        String userNo = decodedJWT.getClaims().get(Sign.CLAIM_USER_NO).asString();
        return userNo;
    }

    public String getUserName(){
        DecodedJWT decodedJWT = common();
        String userName = decodedJWT.getClaims().get(Sign.CLAIM_USER_NAME).asString();
        return userName;
    }

    public String getRoleCode(){
        DecodedJWT decodedJWT = common();
        Claim roleCodeClaim = decodedJWT.getClaims().get(Sign.CLAIM_ROLE_CODE);
        return roleCodeClaim.asString();
    }

    public String getRoleName(){
        DecodedJWT decodedJWT = common();
        Claim roleNameClaim = decodedJWT.getClaims().get(Sign.CLAIM_ROLE_NAME);
        return roleNameClaim.asString();
    }

    private DecodedJWT common () {
        //从请求头中获取token
        String token = RequestDataExtractor.getHeader(request, "token");
        //校验token
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = Sign.verifySessionToken(token, "secret");
        } catch (TokenExpiredException e) {
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return decodedJWT;
    }
}
